package com.alchemystar.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * socket client 采用最简单的短连接
 */
public class TimeClient {

    public static void main(String args[]) throws Exception {
        String host = "127.0.0.1";
        int port = 8888;
        // 与服务端建立连接
        Socket socket = new Socket(host, port);
        // 发送数据
        clientSendCommand(socket);
        // 获取响应
        clientGetResponse(socket);
        socket.close();
    }

    public static void clientSendCommand(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        String message = "Hello which time now\n";
        outputStream.write(message.getBytes("UTF-8"));
        outputStream.flush();
        // 这边需要shutdown,才能让server端的read(bytes)=-1
        socket.shutdownOutput();
    }

    public static void clientGetResponse(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = socket.getInputStream();
        while ((len = inputStream.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len, "UTF-8"));
        }
        System.out.println(sb);
        socket.shutdownInput();
        inputStream.close();
    }
}